<!--自定义表单管理-->
<template>
  <div id="businessForm" class="app-container flex-row">
    <div class="conmmon-container-left scroll__y__content scrollbar-no-width" style="width:300px">
      <category-dict-tree type="06" name="设计表单分类" :level="1" @change="handleCategoryChange" />
    </div>
    <div class="conmmon-container-main flex-main">
      <!--搜索条件-->
      <div class="filter-container">
        <el-form :model="listQuery" :inline="true">
          <el-form-item>
            <el-input v-model="listQuery.code" clearable placeholder="请输入编号" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="listQuery.name" clearable placeholder="请输入名称" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" plain @click="handleFilter">搜索</el-button>
            <el-button icon="el-icon-refresh" plain @click="handleReset">重置</el-button>

          </el-form-item>
        </el-form>
      </div>
      <!--列表-->
      <div class="table-container flex-main">
        <div class="table-container-header">
          <table-toolbar @create="handleCreate" @refresh="handleFilter" @remove="removeRecord" />
        </div>
        <el-table
          ref="multipleTable"
          :data="list"
          header-cell-class-name="table-header"
          fit
          height="100%"
          highlight-current-row
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @sort-change="sortChange">
          <el-table-column type="selection" width="60" />
          <el-table-column align="center" prop="id" label="#" width="60">
            <template slot-scope="scope">{{ scope.$index+1 }}</template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="图标" prop="icon" width="70" align="center">
            <template slot-scope="scope">
              <img :src="common.getFileView(scope.row.icon)" class="common-round-image-32" @error="handleImageError">
            </template>
          </el-table-column>
          <el-table-column label="表单名称" prop="name" min-width="150" sortable align="left">
            <template slot-scope="scope"><span class="color-primary">{{ scope.row.code }}</span>  {{ scope.row.name }}</template>
          </el-table-column>
          <el-table-column label="状态" prop="status" width="80" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.status===0" class="color-success">已发布</span>
              <span v-if="scope.row.status===1" class="color-danger">未发布</span>
            </template>
          </el-table-column>
          <el-table-column prop="createdBy" align="center" label="创建人" width="230" :show-overflow-tooltip="true">
            <template slot-scope="scope">{{ scope.row.createdBy | optionUserFormat }}<br>{{ scope.row.gmtCreated | formatDate }}</template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="160">
            <template slot-scope="scope">
              <button-option icon="el-icon-edit-outline" skin="primary" title="设计" @click="handleDesigner(scope.row)" />
              <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
              <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination_handler">
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
      </div>
    </div>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="businessFormRules"
          :model="businessFormRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="所属分类:" prop="categoryId">
            <category-dict-select v-model="businessFormRecord.categoryId" type="06" placeholder="请输入分类" />
          </el-form-item>
          <el-form-item label="编号:" prop="code">
            <el-input v-model="businessFormRecord.code" disabled show-word-limit placeholder="自动生成" clearable />
          </el-form-item>
          <el-form-item label="名称:" prop="name">
            <el-input v-model="businessFormRecord.name" maxlength="15" show-word-limit placeholder="请输入表单名称" clearable />
          </el-form-item>
          <el-form-item label="图标:" prop="icon">
            <single-image-upload v-model="businessFormRecord.icon" :catalog="constants.FILE_CATALOG_FORM_DESIGN" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>
    <side-box :show="sideBox.designerShow" :title="sideBox.designerTitle" class="side-modal-box-full" @close="sideBox.designerShow=!sideBox.designerShow">
      <template slot="body">
        <fc-designer ref="formDesigner" :config="formConfig" @save="saveFromContent">
          <template #handle>
            <el-dropdown style="margin-right: 10px;">
              <span class="el-dropdown-link">
                导入<i class="el-icon-arrow-down" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="handleDesignerOption('importJson')">导入表单规则(JSON)</el-dropdown-item>
                <el-dropdown-item @click.native="handleDesignerOption('importOption')">导入表单配置(Options)</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-dropdown style="margin-right: 10px;">
              <span class="el-dropdown-link">
                导出<i class="el-icon-arrow-down" />
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="handleDesignerOption('exportJson')">生成表单规则(JSON)</el-dropdown-item>
                <el-dropdown-item @click.native="handleDesignerOption('exportOption')">生成表单配置(Options)</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </fc-designer>
      </template>
      <template slot="foot">
        <el-button :loading="sideBox.buttonLoading" type="primary" @click="saveFromContentConfirm">保存并发布</el-button>
      </template>
    </side-box>
    <model-dialog
      title="再次确认"
      :visible.sync="dialogVisible"
      width="90%"
      @close="dialogVisible=!dialogVisible">
      <el-tabs v-model="activeName">
        <el-tab-pane label="表单规则" name="rule">
          <vue-json-editor
            v-model="formContent"
            style="width: 100%;height: 100%;"
            :show-btns="false"
            mode="form"
            lang="zh"
            :expanded-on-start="true" />
        </el-tab-pane>
        <el-tab-pane label="表单配置" name="option">
          <vue-json-editor
            v-model="formOption"
            style="width: 100%;height: 100%;"
            :show-btns="false"
            mode="form"
            lang="zh"
            :expanded-on-start="true" />
        </el-tab-pane>
      </el-tabs>
      <template slot="footer">
        <el-button type="primary" @click="publishFromContent">保存并发布</el-button>
      </template>
    </model-dialog>
    <model-dialog
      :title="resultTitle"
      :visible.sync="resultDialogVisible"
      width="900px"
      @close="resultDialogVisible=!resultDialogVisible">
      <div class="flex-row" style="padding:20px 0">
        <json-editor ref="jsonEditor" v-model="resultJsonContent" theme="light" />
      </div>
      <template v-if="resultOptionType==='importJson' || resultOptionType==='importOption'" slot="footer">
        <el-button type="primary" @click="handleResultDialogConfirm">确定</el-button>
      </template>
    </model-dialog>
  </div>
</template>

<script>
export default {
  components: {},

  data() {
    return {
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        code: undefined,
        name: undefined,
        categoryId: '-',
        sort: this.common.SORT_DEFAULT
      },

      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create',
        buttonLoading: false,
        designerShow: false,
        designerTitle: '流程表单在线设计'
      },
      businessFormRecord: {},
      businessFormRules: {
        code: [
          { required: true, message: '请输入编号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请输入分类ID', trigger: 'blur' }
        ],
        icon: [
          { required: true, message: '请上传图标', trigger: 'blur' }
        ]
      },
      formDetails: {},
      dialogVisible: false,
      activeName: 'rule',
      formContent: {},
      formOption: {},
      formConfig: {
        showSaveBtn: true
      },
      resultTitle: '设置生成规则',
      resultDialogVisible: false,
      resultJsonContent: null,
      resultOptionType: 'importOption'
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // 表格自带方法开始
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格行数据单击*/
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    /* 搜索*/
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /* 重置*/
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        code: undefined,
        name: undefined,
        sort: this.common.SORT_DEFAULT
      }
      this.$refs.multipleTable.clearFilter()
      this.$refs.multipleTable.clearSort()
      this.fetchData()
    },
    handleCategoryChange(val) {
      console.log(val)
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        code: undefined,
        name: undefined,
        categoryId: val.id !== 0 ? val.id : '',
        sort: this.common.SORT_DEFAULT
      }
      this.fetchData()
    },
    async fetchData() {
      const response = await this.$store.dispatch('businessFormPage', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    /* 新增*/
    handleCreate() {
      this.businessFormRecord = {
        code: this.T.randomString(4)
      }
      this.sideBox = {
        status: 'create',
        recordShow: true,
        title: '新增自定义表单'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('businessFormSave', this.businessFormRecord).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /* 编辑*/
    handleUpdate(row) {
      this.businessFormRecord = Object.assign({}, row) // copy obj
      this.sideBox = {
        status: 'update',
        recordShow: true,
        title: '编辑自定义表单'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.businessFormRecord)
          this.$store.dispatch('businessFormUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('businessFormRemove', ids).then(response => {
            this.handleReset()
            this.$modal.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.$modal.msgWarning('请选择要删除的记录')
      }
    },
    handleDesigner(row) {
      this.$store.dispatch('businessFormGetById', row.id).then((res) => {
        this.formDetails = res
        this.sideBox = {
          designerTitle: `表单在线设计【${row.name}】`,
          designerShow: true
        }
        if (res.formContent) {
          this.$refs.formDesigner.setRule(JSON.parse(res.formContent))
        } else {
          this.$refs.formDesigner.setRule({
            resetBtn: {
              show: false
            },
            submitBtn: {
              show: false
            }
          })
        }
        if (res.formOptions) {
          this.$refs.formDesigner.setOption(JSON.parse(res.formOptions))
        } else {
          this.$refs.formDesigner.setOption({})
        }
      }).catch((_) => {})
    },
    saveFromContentConfirm() {
      this.formContent = this.$refs.formDesigner.getJson()
      if (JSON.parse(this.formContent).length === 0) {
        this.$modal.msgWarning('您还没绘制任何表单内容!')
        return
      }
      this.dialogVisible = true
      this.formContent = JSON.parse(this.$refs.formDesigner.getJson())
      this.formOption = this.$refs.formDesigner.getOption()
    },
    saveFromContent() {
      var resultContent = this.$refs.formDesigner.getJson()
      if (JSON.parse(resultContent).length === 0) {
        this.$modal.msgWarning('您还没绘制任何表单内容!')
        return
      }
      var formOptions = this.$refs.formDesigner.getOption()
      this.$store.dispatch('businessFormSaveContent', {
        id: this.formDetails.id,
        formContent: resultContent,
        formOption: JSON.stringify(formOptions)
      }).then(response => {
        this.$modal.msgSuccess('保存成功')
      }).catch(() => {
        this.sideBox.buttonLoading = false
      })
    },
    publishFromContent() {
      var resultContent = JSON.stringify(this.formContent)
      if (JSON.parse(resultContent).length === 0) {
        this.$modal.msgWarning('您还没绘制任何表单内容!')
        return
      }
      var formOptions = this.$refs.formDesigner.getOption()
      this.$store.dispatch('businessFormPublishContent', {
        id: this.formDetails.id,
        formContent: resultContent,
        formOption: JSON.stringify(formOptions)
      }).then(response => {
        this.$modal.msgSuccess('发布成功')
        this.sideBox = {
          buttonLoading: false,
          formShow: false,
          designerShow: false
        }
        this.dialogVisible = false
        this.handleFilter()
      }).catch(() => {
        this.sideBox.buttonLoading = false
      })
    },
    handleDesignerOption(type) {
      this.resultOptionType = type
      this.resultDialogVisible = true
      if (type === 'exportJson') {
        this.resultTitle = '生成规则'
        this.resultJsonContent = this.$refs.formDesigner.getRule()
      }
      if (type === 'exportOption') {
        this.resultTitle = '表单规则'
        this.resultJsonContent = this.$refs.formDesigner.getOption()
      }
      if (type === 'importJson') {
        this.resultTitle = '设置生成规则'
        this.resultJsonContent = []
      }
      if (type === 'importOption') {
        this.resultTitle = '设置表单规则'
        this.resultJsonContent = {
          'form': {}
        }
      }
    },
    handleResultDialogConfirm() {
      var result = {}
      try {
        result = JSON.parse(this.resultJsonContent)
      } catch (err) {
        this.$modal.msgWarning('请正确填写数据!')
        return
      }
      if (result.length === 0) {
        if (this.resultOptionType === 'importJson') {
          this.$modal.msgWarning('请设置生成规则!')
        }
        if (this.resultOptionType === 'importOption') {
          this.$modal.msgWarning('请设置表单规则!')
        }
        return
      }
      if (this.resultOptionType === 'importJson') {
        this.$refs.formDesigner.setRule(result)
      }
      if (this.resultOptionType === 'importOption') {
        this.$refs.formDesigner.setOption(result)
      }
      this.resultDialogVisible = false
    }

  }
}
</script>
<style lang="scss" scoped>
</style>
